package com.butterfly.hotkey.worker.framework.netty.dashboard;


import com.butterfly.hotkey.core.constant.Constants;
import com.butterfly.hotkey.worker.framework.component.WorkerContainer;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author butterfly
 * @version 1.0
 */
public class WorkerNettyClient {

    private static final Logger log = LoggerFactory.getLogger(WorkerNettyClient.class);

    private final Bootstrap bootstrap;

    private final WorkerContainer workerContainer;

    public WorkerNettyClient(WorkerContainer workerContainer) {
        this.workerContainer = workerContainer;
        bootstrap = initBootstrap();
    }

    private Bootstrap initBootstrap() {
        EventLoopGroup group = new NioEventLoopGroup(2);
        Bootstrap bootstrap = new Bootstrap();
        NettyClientHandler nettyClientHandler = new NettyClientHandler(workerContainer);

        bootstrap.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ByteBuf delimiter = Unpooled.copiedBuffer(Constants.DELIMITER.getBytes());
                        ch.pipeline()
                                .addLast(new DelimiterBasedFrameDecoder(Constants.MAX_LENGTH, delimiter))
                                .addLast(new StringDecoder())
                                .addLast(new StringEncoder())
                                .addLast(new IdleStateHandler(0, 0, 30))
                                .addLast(nettyClientHandler);
                    }
                });
        return bootstrap;
    }

    public synchronized void connect(String address) {
        String[] split = address.split(":");
        try {
            String host = split[0];
            int port = Integer.parseInt(split[1]);
            bootstrap.connect(host, port).sync();
        } catch (Exception e) {
            log.error("connect dashboard fail", e);
        }
    }

}
